package com.szgd.service.personnel;

import com.szgd.bean.SysDict;
import com.szgd.dao.ecdata.personnel.TrainMapper;
import com.szgd.paging.Order;
import com.szgd.paging.PageBounds;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.service.sys.SysDictService;
import com.szgd.util.Constant;
import com.szgd.util.NumberValidation;
import com.szgd.util.StringUtil;
import com.szgd.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TrainService extends SimulateBaseService {
    @Autowired
    TrainMapper trainMapper;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    PersonnelInfoService personnelInfoService;

    public List<Map<String, Object>> getTrainListNoPage(Map<String, Object> params) {
        List<Map<String, Object>>  trainInfoList = trainMapper.getTrainList(params);
        return trainInfoList;
    }

    public List<Map<String, Object>> getTrainList(Map<String, Object> params) {
        String sortColumn = "beginTime"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        return getSqlSession().selectList("com.szgd.dao.ecdata.personnel.TrainMapper.getTrainList", params,pageBounds);
    }

    public Map<String,Object> getTrainDetailInfo(Long id){
        return trainMapper.getTrainDetailInfo(id);
    }

    public void saveTrainInfo(Map<String, Object> params){
        trainMapper.saveTrainInfo(params);
    }

    public int deleteTrain(Map<String, Object> params){
        return trainMapper.deleteTrain(params);
    }

    public List<Map<String, Object>> getTrainRecordList(Map<String, Object> params) {
        String sortColumn = "ID"; //默认的排序列
        String sortType = "desc";
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        return getSqlSession().selectList("com.szgd.dao.ecdata.personnel.TrainMapper.getTrainRecordList", params,pageBounds);
    }

    public List<Map<String, Object>> getAllPerson() {
        List<Map<String, Object>> list = trainMapper.getAllPerson();
        for(int i=0;i<list.size();i++){
            Map<String, Object> map = list.get(i);
            String tel = map.get("TEL")==null?"":map.get("TEL").toString();
            String idNumber = map.get("ID_NUMBER")==null?"":map.get("ID_NUMBER").toString();
            String workType = map.get("DICT_VALUE")==null?"":map.get("DICT_VALUE").toString();
            String inDate = map.get("IN_DATE_S")==null?"":map.get("IN_DATE_S").toString();
            String title = "身份证: "+idNumber+"&#10;联系电话: "+tel+"&#10;岗  位: "+workType+"&#10;入场日期: "+inDate;
            map.put("title",title);
        }
        return list;
    }

    public void insertTrainInfo(Map<String, Object> params){
        trainMapper.insertTrainInfo(params);
    }

    public void insertTrainRecord(Map<String, Object> params){
        trainMapper.insertTrainRecord(params);
    }

    public Map<String, String> getFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("name","人员名称");
        fieldMapping.put("category","培训项目");
        fieldMapping.put("place","培训地点");
        fieldMapping.put("beginTime","培训开始日期");
        fieldMapping.put("endTime","培训结束日期");
        fieldMapping.put("totalTime","培训时间(小时)");
        fieldMapping.put("scoreType","培训结果");

        return fieldMapping;
    }

    public Map<String, Object> batchImportTrain(List<Map<String, Object>> trainList,String userId,String batchNo) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> successList = new ArrayList<>();   //记录导入成功的数据
        List<Map<String, Object>> updateList = new ArrayList<>();   //记录更新的数据
        List<Map<String, Object>> failedList = new ArrayList<>();   //记录导入失败的数据
        List<Map<String, Object>> ignoreList = new ArrayList<>();   //记录忽略的数据


        for (Map<String, Object> trainMap : trainList) {
            HashMap<String, Object> sourceDataMap = new HashMap<String, Object>(trainMap);
            try {
                //判断必填项
                if(trainMap.get("name") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("name")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","人员名称为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(trainMap.get("category") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("category")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","培训项目为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(trainMap.get("place") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("place")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","培训地点为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(trainMap.get("beginTime") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("beginTime")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","培训开始日期为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(trainMap.get("endTime") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("endTime")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","培训结束日期为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(trainMap.get("totalTime") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("totalTime")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","培训时间为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                //判断培训项目
                if(trainMap.get("category") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("category")))) {
                    trainMap.put("PARENT_CODE", "TRAIN_CATEGORY");
                    trainMap.put("DICT_VALUE", trainMap.get("category"));
                    List<SysDict> categoryList = sysDictService.getAllSysDict(trainMap);
                    if (categoryList != null && categoryList.size() > 0) {
                        SysDict dict = categoryList.get(0);
                        trainMap.put("category", dict.getCode());
                    } else {
                        sourceDataMap.put("ERROR_MSG","培训项目填写不正确(参考数据字典)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //验证是否有该人员
                if(trainMap.get("name") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("name")))) {
                    String name = trainMap.get("name").toString();
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("name",name);
                    Map<String, Object> person = personnelInfoService.getPersonnelInfo(temp);
                    if(person==null || person.size()==0){
                        sourceDataMap.put("ERROR_MSG","请校验人员姓名");
                        failedList.add(sourceDataMap);
                        continue;
                    }else{
                        String personnelId = person.get("id").toString();
                        String inDate = person.get("inDate").toString();
                        if(inDate.compareTo(trainMap.get("beginTime").toString()) <=0){
                            sourceDataMap.put("ERROR_MSG","培训日期需在人员的入场日期之前");
                            failedList.add(sourceDataMap);
                            continue;
                        }
                        trainMap.put("personnelId",personnelId);
                    }
                }

                //判断培训结果
                if(trainMap.get("scoreType") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("scoreType")))) {
                    trainMap.put("PARENT_CODE", "SCORE_TYPE");
                    trainMap.put("DICT_VALUE", trainMap.get("scoreType"));
                    List<SysDict> scoreTypeList = sysDictService.getAllSysDict(trainMap);
                    if (scoreTypeList != null && scoreTypeList.size() > 0) {
                        SysDict dict = scoreTypeList.get(0);
                        trainMap.put("scoreType", dict.getCode());
                    } else {
                        sourceDataMap.put("ERROR_MSG","培训结果填写不正确(参考数据字典)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //验证日期是否准确
                if(trainMap.get("beginTime") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("beginTime")))) {
                    String beginTime = trainMap.get("beginTime").toString();
                    boolean res = TimeUtil.isValidDate(beginTime);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","培训开始日期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                if(trainMap.get("endTime") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("endTime")))) {
                    String endTime = trainMap.get("endTime").toString();
                    boolean res = TimeUtil.isValidDate(endTime);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","培训结束日期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                if(trainMap.get("beginTime") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("beginTime")))&&trainMap.get("endTime") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("endTime")))) {
                    String endTime = trainMap.get("endTime").toString();
                    String beginTime = trainMap.get("beginTime").toString();
                    boolean res = TimeUtil.isValidDate(endTime);
                    if(endTime.compareTo(beginTime)<0){
                        sourceDataMap.put("ERROR_MSG","结束日期不能小于开始日期");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                //判断培训时间是否为整型数字
                if(trainMap.get("totalTime") != null && StringUtil.isNotBlank(String.valueOf(trainMap.get("totalTime")))) {
                    String totalTime = trainMap.get("totalTime").toString();
                    boolean res = NumberValidation.isInteger(totalTime);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","培训时间填写不正确(必须为数字)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //每个人每个培训项目只培训一次
                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("personnelId",trainMap.get("personnelId"));
                paramMap.put("category",trainMap.get("category"));
                paramMap.put("beginTime",trainMap.get("beginTime"));
                paramMap.put("endTime",trainMap.get("endTime"));
                List<Map<String, Object>>  trainInfoList =  this.getTrainListNoPage(paramMap);
                if (trainInfoList != null && trainInfoList.size() > 0)
                {
                    trainMap.put("id",trainInfoList.get(0).get("id"));
                    trainMap.put("uploader",userId);
                    trainMapper.saveTrainInfo(trainMap);
                    updateList.add(trainMap);
                }
                else {
                    trainMap.put("creator",userId);
                    trainMapper.insertTrainInfo(trainMap);
                    successList.add(trainMap);
                }
            }catch (Exception e){
                String errorMsg = e.getMessage();
                if(errorMsg.indexOf("###",10) != -1){
                    errorMsg = errorMsg.substring(0,errorMsg.indexOf("###",10));
                }
                sourceDataMap.put("ERROR_MSG",errorMsg);
                //记录导入失败记录
                failedList.add(sourceDataMap);
            }
        }

        //组装本次导入的结果
        resultMap.put(Constant.IMPORT_HE_SUCCESS,successList);
        resultMap.put(Constant.IMPORT_HE_IGNORE,ignoreList);
        resultMap.put(Constant.IMPORT_HE_FAILED,failedList);
        resultMap.put(Constant.IMPORT_HE_UPDATED,updateList);
        return resultMap;
    }
}
